package com.hdkj.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.hdkj.eduservice.entity.ArtSubject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hdkj.eduservice.entity.excel.ArtSubjectData;
import com.hdkj.eduservice.service.ArtSubjectService;
import com.hdkj.handler.GuiliException;

public class ArtSubjectListener extends AnalysisEventListener<ArtSubjectData> {

        //因为SubjectExcelListener不能交给spring进行管理，需要自己new，不能注入其他对象
        //不能实现数据库操作
        public ArtSubjectService artSubjectService;
              public ArtSubjectListener() {
        }
             public ArtSubjectListener(ArtSubjectService artSubjectService) {
            this.artSubjectService = artSubjectService;
        }

        @Override
        public void invoke (ArtSubjectData artsubdata, AnalysisContext analysisContext){
            if (artsubdata == null) {
                throw new GuiliException(20001, "文件数据为空");
            }

            //一行一行读取，每次读取有两个值，第一个值一级分类，第二个值二级分类
            //判断一级分类是否重复
            ArtSubject existOneSubject = this.existOneSubject(artSubjectService, artsubdata.getOneSubjectName());
            if (existOneSubject == null) { //没有相同一级分类，进行添加
                existOneSubject = new ArtSubject();
                existOneSubject.setParentId("0");
                existOneSubject.setTitle(artsubdata.getOneSubjectName());//一级分类名称
                artSubjectService.save(existOneSubject);
            }

            //获取一级分类id值
            String pid = existOneSubject.getId();

            //添加二级分类
            //判断二级分类是否重复
            ArtSubject existTwoSubject = this.existTwoSubject(artSubjectService, artsubdata.getTwoSubjectName(), pid);
            if (existTwoSubject == null) {
                existTwoSubject = new ArtSubject();
                existTwoSubject.setParentId(pid);
                existTwoSubject.setTitle(artsubdata.getTwoSubjectName());//二级分类名称
                artSubjectService.save(existTwoSubject);
            }
        }

        //判断一级分类不能重复添加
        private ArtSubject existOneSubject (ArtSubjectService artSubjectService, String name){
            QueryWrapper<ArtSubject> wrapper = new QueryWrapper<>();
            wrapper.eq("title", name);
            wrapper.eq("parent_id", "0");
            ArtSubject oneSubject = artSubjectService.getOne(wrapper);
            return oneSubject;
        }

        //判断二级分类不能重复添加
        private ArtSubject existTwoSubject (ArtSubjectService artSubjectService, String name, String pid){
            QueryWrapper<ArtSubject> wrapper = new QueryWrapper<>();
            wrapper.eq("title", name);
            wrapper.eq("parent_id", pid);
            ArtSubject twoSubject = artSubjectService.getOne(wrapper);
            return twoSubject;
        }

        @Override
        public void doAfterAllAnalysed (AnalysisContext analysisContext){


        }

}
